﻿#include "dialogonline.h"
#include "ui_dialogonline.h"

#include <QShowEvent>
#include <QPainter>
#include <QPainterPath>
#include <QLabel>
#include <QByteArray>
#include <QTimer>
#include <QCloseEvent>

dialogOnline::dialogOnline(QWidget *parent, QTcpSocket* tempSocket) :
    QDialog(parent),
    ui(new Ui::dialogOnline),
    m_tcpSocket(tempSocket)
{
    ui->setupUi(this);
    setAttribute(Qt::WA_DeleteOnClose);
    init();
}

dialogOnline::~dialogOnline()
{
    delete ui;
}

void dialogOnline::init()
{
    // 初始化一些背景属性
    setWindowFlags(this->windowFlags() | Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);
    QPoint tempPos = static_cast<QWidget*>(parent())->pos();
    QSize tempSize = static_cast<QWidget*>(parent())->size();
    this->move(tempPos.x() + 8, tempPos.y() + 38);
    this->resize(tempSize);

    // 初始化标签
    ui->labelSelf->setPixmap(QPixmap(":/Monster_Kill/Res/Img/state.png"));
    ui->labelRival->setPixmap(QPixmap(":/Monster_Kill/Res/Img/state.png"));

    // 初始化TCP并自动发起连接
    connect(m_tcpSocket, &QTcpSocket::readyRead, this, &dialogOnline::tcpInfoHandle);
    connect(m_tcpSocket,
            QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error),
            [this](QAbstractSocket::SocketError e){
        QString str = e + m_tcpSocket->errorString();
        qDebug() << str;
    });
    connect(m_tcpSocket, &QTcpSocket::connected, [this](){
        updateHead(upIndex::SHOW_SLEF);
    });

    m_tcpSocket->connectToHost(gTcpIP, gTcpPort);

}

void dialogOnline::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    QPixmap tempPixmap(":/Monster_Kill/Res/Img/Hall.jpg");

    QPainterPath path;
    QRectF tempRect = this->rect();
    tempRect.setWidth(1052);
    path.addRoundedRect(tempRect, 10, 10);

    painter.setClipPath(path);
    painter.drawPixmap(this->rect(), tempPixmap);

}

void dialogOnline::updateHead(upIndex index)
{
    // 绘制头像
    QPixmap* tempPixmap = new QPixmap(":/Monster_Kill/Res/Img/state.png");
    QPainter painter(tempPixmap);
    QPixmap src(":/Monster_Kill/Res/Img/head.png");
    QPixmap mask(":/Monster_Kill/Res/Img/head_mask.png");
    QPixmap head = getRoundHead(src, mask, QSize(107, 107));
    painter.drawPixmap(143 - 51 - 6, 161 - 51 - 62, head.width(), head.height(), head);

    // 绘制匹配状态
    QFont tempFont; tempFont.setFamily("华文琥珀"); tempFont.setPointSize(28);
    painter.setFont(tempFont);
    painter.setPen(Qt::magenta);
    painter.drawText(70, 252, "已准备");

    switch (index) {
    case upIndex::SHOW_SLEF:

        ui->labelSelf->setPixmap(*tempPixmap);
        break;
    case upIndex::SHOW_RIVAL:

        ui->labelRival->setPixmap(*tempPixmap);
        break;
    default:
        break;
    }
}

void dialogOnline::tcpInfoHandle()
{
    while(m_tcpSocket->bytesAvailable() >= sizeof(quint32)){
        QByteArray bt;
        QDataStream in(m_tcpSocket);
        in.setVersion(QDataStream::Qt_5_0);

        // 读取数据大小
        quint32 btSize;
        in >> btSize;
        if(m_tcpSocket->bytesAvailable() < btSize - sizeof(quint32)){
            break;
        }

        bt.resize(btSize - sizeof(quint32));
        in.readRawData(bt.data(), bt.size());

        QString tempStr = QString::fromUtf8(bt);
        tcpInfoResponse(tempStr);
    }
}

void dialogOnline::tcpInfoResponse(QString str)
{
    if(str == "555"){
        qDebug() << "已连接服务器";

    }else if(str == "888"){
        qDebug() << "所有玩家已准备就绪";
        updateHead(upIndex::SHOW_RIVAL);
        ui->labelCon->setText("匹配成功");
        // 延长发送时间1.8s
        QTimer* timer = new QTimer();
        timer->start(1800);
        timer->setSingleShot(true);
        connect(timer, &QTimer::timeout, this, &dialogOnline::signal_succ);

    }else{
        qDebug() << "解包错误" << endl;
    }
}

QPixmap dialogOnline::getRoundHead(const QPixmap &src, QPixmap &mask, QSize maskSize)
{
    if(maskSize == QSize(0, 0)){
        maskSize = mask.size();
    }else{
        mask.scaled(maskSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    }

    QImage resultImage(maskSize,QImage::Format_ARGB32_Premultiplied);
    QPainter painter(&resultImage);
    painter.setCompositionMode(QPainter::CompositionMode_Source); // 混合模式
    painter.fillRect(resultImage.rect(), Qt::transparent);
    painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
    painter.drawPixmap(0, 0, mask);
    painter.setCompositionMode(QPainter::CompositionMode_SourceIn);
    painter.drawPixmap(0, 0, src.scaled(maskSize, Qt::KeepAspectRatio, Qt::SmoothTransformation));

    return QPixmap::fromImage(resultImage);
}

void dialogOnline::on_exitBtn_clicked()
{
    emit signal_exit();
}

void dialogOnline::closeEvent(QCloseEvent* e)
{
    disconnect(m_tcpSocket, &QTcpSocket::readyRead,
               this, &dialogOnline::tcpInfoHandle);
    QDialog::closeEvent(e);
}
